package com.epfresh.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import com.epfresh.api.widget.PhotoUploadView;
import com.epfresh.R;
import com.epfresh.activity.MoreEvaluateActivity;
import com.epfresh.api.adapter.CommonAdapter;
import com.epfresh.api.adapter.ViewHolder;
import com.epfresh.api.entity.*;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.http.HttpRequest;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.universalimageloader.core.DisplayImageOptions;
import com.epfresh.api.universalimageloader.core.ImageLoader;
import com.epfresh.api.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.epfresh.api.universalimageloader.core.imageaware.ImageViewAware;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.api.widget.list.LoadMoreListView;
import com.epfresh.api.widget.ptr.PtrDefaultHandler;
import com.epfresh.api.widget.ptr.PtrFrameLayout;
import com.epfresh.api.widget.ptr.PtrHandler;
import com.epfresh.api.widget.ptr.PtrMdFrameLayout;
import com.epfresh.bean.ContentEntity;
import com.epfresh.bean.Evaluate;
import com.epfresh.global.BaseApplication;
import com.epfresh.global.BaseFragment;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/*
        addressText = (TextView)v.findViewById(R.id.address_text);
        addressText.setOnClickListener(this);
*/

/**
 * Created by wzh on 2016/5/4.
 */
@SuppressLint("ValidFragment")
public class EvaluatesListFragment extends BaseFragment implements LoadMoreListView.IXListViewListener {
    ArrayList<Evaluate> evaluates;
    private LoadMoreListView mListView;
    Context mContext;
    private RelativeLayout nodate_ll;
    EvaluateAdapter adapter;
    int page = 0;
    String level = "";
    boolean isOnCreatedView;
    /**
     * 使用了github开源的ImageLoad进行了数据加载
     */
/*    static ImageLoader imageLoader;
    static DisplayImageOptions options;*/
    int evaluateType = 1;
    public EvaluatesListFragment() {
    }
    public EvaluatesListFragment(int newsType,int evaluateType) {
        if (newsType == 0) {
            this.level = "";
            this.evaluateType = evaluateType;
            this.level = "" + newsType;
            return;
        }
        this.evaluateType = evaluateType;
        this.level = "" + newsType;
        Log.i("" + newsType, "newsType");
    }

    @Override
    public String getBaseTag() {
        return "EvaluatesListFragment";
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        mContext = this.getActivity();
        View view = inflater.inflate(R.layout.fragment_list_evaluate, container, false);
        mListView = (LoadMoreListView) view.findViewById(R.id.listview);
        nodate_ll = (RelativeLayout) view.findViewById(R.id.rl_nodate);
        evaluates = new ArrayList<Evaluate>();
        adapter = new EvaluateAdapter(mContext, evaluates,
                R.layout.item_comment);
        mListView.setAdapter(adapter);
        mListView.setPullLoadEnable(false); // 设置可滑动
        mListView.setXListViewListener(this);// 设置滑动监听器

        isOnCreatedView = true;
        initHeadView(view);
        refresh();
        return view;
    }


    private PtrMdFrameLayout ptrFrameLayout;
    private PtrHandler ptrHandler = new PtrHandler() {
        @Override
        public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
            return PtrDefaultHandler.checkContentCanBePulledDown(frame, mListView, header);
        }

        @Override
        public void onRefreshBegin(PtrFrameLayout frame) {
            refresh();
        }
    };

    private void initHeadView(View view) {
        ptrFrameLayout = (PtrMdFrameLayout) view.findViewById(R.id.fragment_ptr_home_ptr_frame);
        ptrFrameLayout.setPtrHandler(ptrHandler);
//        ptrFrameLayout.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                ptrFrameLayout.autoRefresh(true);
//            }
//        }, 200);
    }

    public void refresh() {
        if (mListView != null) {
            mListView.resetNoMore();
        }
        expectPage = 0;
        requestOrderList(0);
    }


    @Override
    public void onLoadMore() {
        if (mLastFlag) {
            mListView.stopLoadMoreNoMore();
        } else {
            expectPage = currentPage + 1;
            requestOrderList(expectPage);
        }
    }

    boolean mLastFlag = false;
    //当前分页
    private int currentPage = 0;
    //期望的分页
    private int expectPage = 0;
    private RequestTag requestTag = new RequestTag();

    public void requestOrderList(int page) {
        if (!isOnCreatedView) {
            if (mListView != null) {
                ptrFrameLayout.refreshComplete();
                mListView.stopLoadMore();
            }
            return;
        }

        //String token = getUser().getToken();
        String uuid = AppUtils.getUniquePsuedoID();
        RequestEntityPurchase<Map<String, String>> entity = new RequestEntityPurchase<>();
        Map<String, String> map = new HashMap<>();
        map.put("level", level);
        map.put("pageNumber", page + "");
        map.put("pageSize", 10 + "");
        if(evaluateType==1){
            map.put("productId", MoreEvaluateActivity.id);
            entity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_comment_list);
            requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_comment_list;
        }else{
            map.put("storeId", MoreEvaluateActivity.id);
            entity.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_comment_list4store);
            requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_comment_list4store;
        }
        map.put("sortProperty", "time");
        map.put("sortDirection", "DESC");
        //entity.setToken(token);
        entity.setClientIdentifierCode(uuid);
        entity.setParameters(map);

        requestTag.action = page;

        request(entity, requestTag, onRequestListener);

    }

    OnRequestListener<ContentEntity<Evaluate>> onRequestListener = new OnRequestListener<ContentEntity<Evaluate>>() {
        @Override
        public ContentEntity<Evaluate> jsonToObj(String responseStr) {
            return new Gson().fromJson(responseStr, new TypeToken<ContentEntity<Evaluate>>() {
            }.getType());
        }
        @Override
        public void onFail(int failCode, Object arg, Object tag) {
            updateView(tag);
            switch (failCode) {
                case HttpRequest.FAIL_NOT_FOUND:

                    break;
                case HttpRequest.FAIL_NO_NET:

                    break;
                case HttpRequest.FAIL_NET_FAULT:

                default:

                    break;
            }
        }

        @Override
        public void onResponseError(int failCode, Object arg, Object tag) {
            updateView(tag);
            normalView();
        }

        @Override
        public void onStart(Object tag) {

        }

        @Override
        public void onResponse(ResponseEntity<ContentEntity<Evaluate>> response, Object tag) {
            normalView();
            ContentEntity<Evaluate> orderResponse = response.getResponseElement();
            mLastFlag = orderResponse.getLast();
            boolean isRefresh = updateView(tag);
            List<Evaluate> content = orderResponse.getContent();
            currentPage = orderResponse.getNumber();
            if (content != null && content.size() > 0) {
                if (isRefresh) {
                    mListView.setPullLoadEnable(true);
                    if (mLastFlag) {
                        mListView.noMore();
                    }
                    evaluates.clear();
                }
                evaluates.addAll(content);
                adapter.notifyDataSetChanged();

            } else {
                //没有数据
                if (isRefresh) {
                    evaluates.clear();
                    noDataView();
                }
            }



        }
    };

    private boolean updateView(Object tag) {
        if (tag != null) {
            RequestTag requestTag = (RequestTag) tag;
            if (requestTag.action == 0) {
                ptrFrameLayout.refreshComplete();
                return true;
            } else {
                if (mLastFlag) {
                    mListView.stopLoadMoreNoMore();
                } else {
                    mListView.stopLoadMore();
                }
            }
        } else {
            ptrFrameLayout.refreshComplete();
            if (mLastFlag) {
                mListView.stopLoadMoreNoMore();
            } else {
                mListView.stopLoadMore();
            }
        }
        return false;
    }


    public void noDataView() {
        mListView.setVisibility(View.GONE);
        nodate_ll.setVisibility(View.VISIBLE);
    }

    public void normalView() {
        mListView.setVisibility(View.VISIBLE);
        nodate_ll.setVisibility(View.GONE);
    }

    class EvaluateAdapter extends CommonAdapter<Evaluate> {

        public EvaluateAdapter(Context context, ArrayList<Evaluate> runPacks, int a) {
            super(context, runPacks, a);
        }

        @Override
        public void convert(final ViewHolder holder, final Evaluate bean) {
            holder.setText(R.id.name, bean.getNickname());
            holder.setText(R.id.time, bean.getTime());
            holder.setText(R.id.content, bean.getContent());
            //holder.setRating(R.id.ratingBar, bean.getTotalScore());
            //ImageLoader.getInstance().displayImage(bean.getAvatar(), new ImageViewAware((ImageView) holder.getView(R.id.pic)), BaseApplication.getAvatarOptions(bean.getAvatar()), null, null, null);
            //holder.setText(R.id.tv_title, bean.getProductName());
            if(bean.getScore()==1){
                holder.setText(R.id.tv_comment_state,"吐槽");
                ((TextView)holder.getView(R.id.tv_comment_state)).setTextColor(Color.parseColor("#626262"));
                holder.setImageResource(R.id.iv_comment_state,R.mipmap.comment_1_small);
            }else if(bean.getScore()==2){
                holder.setText(R.id.tv_comment_state,"满意");
                ((TextView)holder.getView(R.id.tv_comment_state)).setTextColor(Color.parseColor("#ff9600"));
                holder.setImageResource(R.id.iv_comment_state,R.mipmap.comment_2_small);
            }else {
                holder.setText(R.id.tv_comment_state,"点赞");
                ((TextView)holder.getView(R.id.tv_comment_state)).setTextColor(Color.parseColor("#ff0000"));
                holder.setImageResource(R.id.iv_comment_state,R.mipmap.comment_3_small);
            }
            holder.getView(R.id.pu_cover_1).setVisibility(View.INVISIBLE);
            holder.getView(R.id.pu_cover_2).setVisibility(View.INVISIBLE);
            holder.getView(R.id.pu_cover_3).setVisibility(View.INVISIBLE);
            if(bean.getAttachmentUrls()==null||bean.getAttachmentUrls().length==0){
                holder.getView(R.id.ll_cover).setVisibility(View.GONE);
            }else {
                holder.getView(R.id.ll_cover).setVisibility(View.VISIBLE);
                switch (bean.getAttachmentUrls().length){
                    case 1:
                        holder.getView(R.id.pu_cover_1).setVisibility(View.VISIBLE);
                        ImageLoader.getInstance().displayImage(bean.getAttachmentUrls()[0], new ImageViewAware((ImageView) holder.getView(R.id.pu_cover_1)));
                        break;
                    case 2:
                        holder.getView(R.id.pu_cover_1).setVisibility(View.VISIBLE);
                        holder.getView(R.id.pu_cover_2).setVisibility(View.VISIBLE);
                        ImageLoader.getInstance().displayImage(bean.getAttachmentUrls()[0], new ImageViewAware((ImageView) holder.getView(R.id.pu_cover_1)));
                        ImageLoader.getInstance().displayImage(bean.getAttachmentUrls()[1], new ImageViewAware((ImageView)holder.getView(R.id.pu_cover_2)));
                        break;
                    case 3:
                        holder.getView(R.id.pu_cover_1).setVisibility(View.VISIBLE);
                        holder.getView(R.id.pu_cover_2).setVisibility(View.VISIBLE);
                        holder.getView(R.id.pu_cover_3).setVisibility(View.VISIBLE);
                        ImageLoader.getInstance().displayImage(bean.getAttachmentUrls()[0], new ImageViewAware((ImageView) holder.getView(R.id.pu_cover_1)));
                        ImageLoader.getInstance().displayImage(bean.getAttachmentUrls()[1], new ImageViewAware((ImageView)holder.getView(R.id.pu_cover_2)));
                        ImageLoader.getInstance().displayImage(bean.getAttachmentUrls()[2], new ImageViewAware((ImageView) holder.getView(R.id.pu_cover_3)));
                        break;
                }
            }
/*            if (1==bean.getProductType()) {//现售
                ((TextView)holder.getView(R.id.tv_type)).setText("现");
                ((TextView)holder.getView(R.id.tv_type)).setBackgroundResource(R.drawable.good_type_bg);
                ((TextView)holder.getView(R.id.tv_type)).setTextColor(Color.RED);

            } else if (2==bean.getProductType()) {//预售
                ((TextView)holder.getView(R.id.tv_type)).setText("预");
                ((TextView)holder.getView(R.id.tv_type)).setBackgroundResource(R.drawable.good_type_pre_bg);
                ((TextView)holder.getView(R.id.tv_type)).setTextColor(Color.parseColor("#43adea"));

            } else {
                ((TextView)holder.getView(R.id.tv_type)).setText("现");
                ((TextView)holder.getView(R.id.tv_type)).setBackgroundResource(R.drawable.good_type_bg);
                ((TextView)holder.getView(R.id.tv_type)).setTextColor(Color.RED);
            }*/

            if (1 == evaluateType) {
                holder.getView(R.id.ll_title).setVisibility(View.GONE);
                return;
            } else {
                holder.setText(R.id.tv_title, bean.getProductName());
                holder.getView(R.id.ll_title).setVisibility(View.VISIBLE);
/*                if (2 == (bean.getProductType())) {//预售
                    //holder.getView(R.id.tv_type).setVisibility(View.VISIBLE);
                    String html = "<font color=\"#00ffffff\">a预售】</font>" + bean.getProductName();
                    ((TextView) holder.getView(R.id.tv_title)).setText(Html.fromHtml(html));
                } else {//现售
                    //holder.getView(R.id.tv_type).setVisibility(View.GONE);
                    ((TextView) holder.getView(R.id.tv_title)).setText(bean.getProductName());
                }*/
            }

        }
    }
}